#include "runthread.h"
#include <QDebug>

runThread::runThread(QObject *parent)
{
    STOPTYPE = false;

}


// 新线程入口
// 初始化和操作放在这里
void runThread::run(){

    while(!STOPTYPE){
//    qDebug()<<"run()开始";
//    qDebug()<<"run 子线程:"<<QThread::currentThread()<<'\n';
    searchPort();
    QThread::msleep(1000);//强制当前线程时间


}
    STOPTYPE = false;
    exec();
}

void runThread::stop()
{
    STOPTYPE = true;
}


int lengthList = 1;
void runThread::searchPort(){

    QStringList PortList;

        foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
        {

            serialport= new QSerialPort;
            serialport->setPort(info);
            PortList.append("");
            if (serialport->open(QIODevice::ReadWrite))
            {
                PortList.append(info.portName());
            }
            serialport->close();
            delete serialport;
         }
//        qDebug()<<"串口列表："<<PortList;
        removeListSame(&PortList);
        if(PortList.length()>lengthList){
            emit emitPortList(PortList);
            lengthList = PortList.length();
        }
}

void runThread::removeListSame(QStringList *list)
{
    for (int i = 0; i < list->count(); i++)
    {
        for (int k = i + 1; k <  list->count(); k++)
        {
            if ( list->at(i) ==  list->at(k))
            {
                list->removeAt(k);
                k--;
            }
        }
    }

}
